import numpy as np
import operator
import pandas as pd
from sklearn.model_selection import  train_test_split
from sklearn.preprocessing import normalize,StandardScaler
import time
def knn(test,traindata,labels,k):
    # 获得训练数据的size
    traindatasize=traindata.shape[0]
    # 将测试数据扩展然后减去训练数据
    diffmatrix=np.tile(test,(traindatasize,1))-traindata
    # 先平方
    sqdiffmatrix=diffmatrix**2
    # 求和
    sqdistance=sqdiffmatrix.sum(axis=1)
    # 开方
    distance=sqdistance**0.5
#   返回从小到大的索引值
    sortedindex=distance.argsort()
    classcout={}
    for i in range(k):
        thislabel=labels[sortedindex[i]]
        classcout[thislabel]=classcout.get(thislabel,0)+1
#     对于classcount进行排序
    sortedclasscout=sorted(classcout.items(),key=operator.itemgetter(1),reverse=True)
    return sortedclasscout[0][0]
# 读取数据
data=pd.read_csv('iris.csv',names=[1,2,3,4,'label'])
# 将数据按照训练数据和测试数据进行切分
X=data[[1,2,3,4]].values
# # 进行正则化
# X=normalize(X)
# 进行标准化
X=StandardScaler().fit_transform(X)
y=data['label'].values
# 进行模型评估 运行10次
acclist=[]
time1=time.time()
for i in range(10):
    X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)
    right_count=0
    for thistest,thislabel in zip(X_test,y_test):
        result=knn(test=thistest,traindata=X_train,labels=y_train,k=10)
        if result==thislabel:
            right_count+=1
        print(thistest)
        print("预测的结果是："+result)
    acc=right_count/len(X_test)
    acclist.append(acc)
    print("预测的准确率为：{}".format(acc))
avg_acc=np.array(acclist).mean()
print("运行10次的平均准确率为：{}".format(avg_acc))
time2=time.time()
print("运行10次的时间为：{}".format(time2-time1))
